package com.bear.fastrepair.mvvm.ui.employee.adapter

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bear.fastrepair.R
import com.bear.fastrepair.base.BaseViewHolder
import com.bear.fastrepair.databinding.*
import com.bear.fastrepair.entity.*
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.mvvm.ui.employee.dialog.ImageDialog
import com.bear.fastrepair.mvvm.ui.employee.fragment.OrderDetailFragment
import com.bear.fastrepair.utils.CLOCK_IN
import com.bear.fastrepair.utils.MACHINE_TAKE_BACK
import com.bear.fastrepair.utils.ORDER_PREPARE
import com.bear.fastrepair.utils.OpenLocalMapUtil
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

class OrderDetailAdapter(
    private val data: ArrayList<ItemType>,
    private val viewModel: EmployeeViewModel,
    private val context: Context,
    private val fragment: OrderDetailFragment,
    private val serviceOrderId: String,
    private val personalInfo: EmployeeInfo2
) : RecyclerView.Adapter<BaseViewHolder<*>>() {

    var imagesListener: ((List<Uri>) -> Unit)? = null
    var bitmapListener: ((Bitmap) -> Unit)? = null
    var clickBillCommit: (() -> Unit)? = null
    var clickBillLog: (() -> Unit)? = null
    var clickBooking: ((((Array<String>) -> Unit)) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*> =
        when (viewType) {
            0 -> {
                val binding = ItemOrderEmployeeDetailBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                DetailHolder(binding)
            }
            1 -> {
                val binding =
                    ItemOrderLogBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                LogHolder(binding)
            }
            2 -> {
                val binding = ItemImageOriginalBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                ImageHolder(binding)
            }
            3 -> {
                val binding = ItemUploadImageBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                UploadImageHolder(binding)
            }
            4 -> {
                val binding = ItemOrderImagesBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                OrderImagesHolder(binding)
            }
            5 -> {
                val binding =
                    ItemSeparatorBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                OrderImagesSeparator(binding)
            }
            else -> throw IllegalArgumentException("no such view type")
        }

    override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) {
        when (holder) {
            is DetailHolder -> holder.bind(data[position] as DetailDataType, position)
            is ImageHolder -> holder.bind(data[position] as ImagesType, position)
            is UploadImageHolder -> holder.bind(data[position] as UploadImagesType, position)
            is LogHolder -> holder.bind(data[position] as OrderLogType, position)
            is OrderImagesHolder -> holder.bind(data[position] as OrderImagesType, position)
            is OrderImagesSeparator -> holder.bind(data[position] as SeparatorType, position)
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun getItemViewType(position: Int): Int {
        return data[position].itemType
    }

    inner class DetailHolder(private val binding: ItemOrderEmployeeDetailBinding) :
        BaseViewHolder<DetailDataType>(binding.root) {
        @SuppressLint("SetTextI18n")
        override fun bind(item: DetailDataType, index: Int) {
            binding.address.text = "${item.data?.locationAddress}${item.data?.addressDetail}"
            binding.orderStatus.text = item.data?.serviceOrderStatusText
            binding.clientName.text = item.data?.clientName
            binding.clientTel.text = item.data?.clientTel
            binding.orderNumber.text = item.data?.orderNo
            binding.orderTitle.text = item.data?.description
            binding.callLl.setOnClickListener {
                val intent = Intent().apply {
                    action = Intent.ACTION_DIAL
                    data = Uri.parse("tel:${item.data?.clientTel}")
                }
                ActivityUtils.startActivity(intent)
            }
            binding.mapLl.setOnClickListener {
                try {
                    val latitude = personalInfo.data.locationLatitude
                    val longitude = personalInfo.data.locationLongitude
                    val address = personalInfo.data.locationAddress
                    val destination = item.data?.locationAddress
                    val destinationLatitude = item.data?.locationLatitude
                    val destinationLongitude = item.data?.locationLongitude
                    val uri = OpenLocalMapUtil.getGdMapUri("小熊快修", latitude, longitude, address, destinationLatitude.toString(),
                        destinationLongitude.toString(), destination)
                    val intent = Intent(Intent.ACTION_VIEW).apply {
                        val uriString = "androidamap://navi?sourceApplication=${"小熊快修"}&lat=$destinationLatitude&lon=$destinationLongitude&dev=1&style=2"
                        addCategory(Intent.CATEGORY_DEFAULT)
                        setPackage("com.autonavi.minimap")
                        data = Uri.parse(uri)
                    }
                    context.startActivity(intent)
                } catch (e: ActivityNotFoundException) {
                    ToastUtils.showLong("请下载高德地图以使用导航")
                }
            }
            if (item.data?.serviceOrderStatus != ORDER_PREPARE) {
                binding.bookingTime.visibility = View.GONE
            }
            if (!TextUtils.isEmpty(item.data?.appointStartTime)) {
                binding.hintBooking.visibility = View.GONE
                binding.tvBookingStart.text = StringUtils.getString(R.string.booking_start) + item.data?.appointStartTime
                binding.tvBookingEnd.text = StringUtils.getString(R.string.booking_end) + item.data?.appointEndTime
            }
            binding.bookingTime.setOnClickListener {
                clickBooking?.invoke {
                    if (!it.isNullOrEmpty()) {
                        if (item.data?.serviceOrderStatus != ORDER_PREPARE) {
                            binding.bookingTime.visibility = View.GONE
                        }
                        binding.tvBookingStart.text = StringUtils.getString(R.string.booking_start) + it[0]
                        binding.tvBookingEnd.text = StringUtils.getString(R.string.booking_end) + it[1]
                        viewModel.saveBookingTime(serviceOrderId, BookingBody(it[1], it[0]))
                    }
                }

            }
        }
    }

    inner class ImageHolder(private val binding: ItemImageOriginalBinding) :
        BaseViewHolder<ImagesType>(binding.root) {
        override fun bind(item: ImagesType, index: Int) {
            if (item.data?.serviceOrderStatus == CLOCK_IN
                || item.data?.serviceOrderStatus == MACHINE_TAKE_BACK
            ) {
                binding.billCommit.visibility = View.VISIBLE
            } else {
                binding.billCommit.visibility = View.GONE
            }
            binding.billCommit.setOnClickListener {
                clickBillCommit?.invoke()
            }
            binding.billLog.setOnClickListener {
                clickBillLog?.invoke()
            }
            if (item.list.isEmpty()) return
            binding.uploadImageRv.apply {
                layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                adapter = ImageAdapter(item.list, item.itemType)
            }
        }
    }

    inner class UploadImageHolder(private val binding: ItemUploadImageBinding) :
        BaseViewHolder<UploadImagesType>(binding.root) {
        override fun bind(item: UploadImagesType, index: Int) {
            binding.uploadImageRv.apply {
                layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                adapter = ImageAdapter(item.list, item.itemType)
            }
        }
    }

    inner class LogHolder(private val binding: ItemOrderLogBinding) :
        BaseViewHolder<OrderLogType>(binding.root) {
        @SuppressLint("SetTextI18n")
        override fun bind(item: OrderLogType, index: Int) {
            binding.logTime.text = item.log?.createTime
            binding.logContent.text = item.log?.remark
            binding.owner.text = "处理人：${item.log?.userName}"
        }
    }

    inner class OrderImagesSeparator(private val binding: ItemSeparatorBinding) :
        BaseViewHolder<SeparatorType>(binding.root) {
        override fun bind(item: SeparatorType, index: Int) {
            binding.separatorTitle.text = item.data
        }
    }

    inner class OrderImagesHolder(private val binding: ItemOrderImagesBinding) :
        BaseViewHolder<OrderImagesType>(binding.root) {
        override fun bind(item: OrderImagesType, index: Int) {
            binding.include2.logTime.text = item.data.createTime
            binding.include2.logContent.text = item.data.description
            binding.rvOrderImages.let {
                if (item.data.images.isEmpty()) return@let
                it.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                val imageData = item.data.images.split(",").filter { url -> url.isNotEmpty() }
                    .map { url -> BitmapInfo(url = url) }
                val imageDataList = ArrayList<BitmapInfo>().apply { addAll(imageData) }
                it.adapter = ImageAdapter(imageDataList, item.itemType)
            }
        }
    }

    // 切记，嵌套的item，外层不可以再加上ViewGroup
    @SuppressLint("NotifyDataSetChanged")
    inner class ImageAdapter(val list: ArrayList<BitmapInfo>, private val type: Int) :
        RecyclerView.Adapter<BaseViewHolder<BitmapInfo>>() {

        init {
            if (type == 3) {
                imagesListener = imagesListener@{
//                    val last = list.last()
                    list.addAll(0, it.map { uri -> BitmapInfo(uri = uri) })
//                    list.remove(last)
//                    list.addAll(it.map { uri -> BitmapInfo(uri = uri) })
//                    list.add(last)
                    this.notifyDataSetChanged()
                }
                bitmapListener = {
                    list.add(0, BitmapInfo(ImageUtils.save2Album(it, Bitmap.CompressFormat.JPEG)))
                    this.notifyDataSetChanged()
                }
            }
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BaseViewHolder<BitmapInfo> {
            return Holder(
                ItemImageBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: BaseViewHolder<BitmapInfo>, position: Int) {
            if (list.isEmpty()) return
            holder.bind(list[position], position)
        }

        override fun getItemCount(): Int {
            return list.size
        }

        inner class Holder(private val binding: ItemImageBinding) :
            BaseViewHolder<BitmapInfo>(binding.root) {
            @SuppressLint("CheckResult")
            override fun bind(item: BitmapInfo, index: Int) {
                item.let {
                    when {
                        it.file != null -> {
                            Glide.with(context).load(it.file).into(binding.itemImage)
                        }
                        it.resId != null -> {
                            Glide.with(context).load(it.resId).into(binding.itemImage)
                        }
                        it.uri != null -> {
                            Glide.with(context).load(it.uri).into(binding.itemImage)
                        }
                        it.url != null -> {
                            Glide.with(context).load(it.url)
                                .into(binding.itemImage)
                        }
                        else -> Unit
                    }
                }
                if (index == (list.size - 1)) {
                    binding.itemImage.setOnClickListener {
                        if (type == 3) {
                            checkAndOpenGallery { openCamera() }
                        } else {
                            ImageDialog(context, item).show()
                        }
                    }
                } else {
                    binding.itemImage.setOnClickListener {
                        ImageDialog(context, item).show()
                    }
                }
            }

            private fun checkAndOpenGallery(block: () -> Unit) {
                if (!XXPermissions.isGranted(
                        context,
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE
                    )
                ) {
                    XXPermissions.with(context).permission(
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE
                    ).request(object : OnPermissionCallback {
                        override fun onGranted(
                            permissions: MutableList<String>?,
                            all: Boolean
                        ) {
                            block()
                        }

                        override fun onDenied(
                            permissions: MutableList<String>?,
                            never: Boolean
                        ) {
                            super.onDenied(permissions, never)
                            ToastUtils.showLong("没有读写手机图片权限，请授予")
                            XXPermissions.startPermissionActivity(context)
                        }
                    })
                } else {
                    block()
                }
            }

            fun openGallery() {
                val intent = Intent().apply {
                    type = "image/*"
                    putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                    action = Intent.ACTION_GET_CONTENT
                    data = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                }
                ActivityUtils.startActivityForResult(fragment, intent, 1001)
            }

            fun openCamera() {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                ActivityUtils.startActivityForResult(fragment, intent, 1002)
            }
        }
    }
}

